package com.example.coursedesign.ui.home.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.view.ContextThemeWrapper;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;
import com.example.coursedesign.R;
import com.example.coursedesign.ui.home.entity.Medicine;
import com.google.android.material.chip.Chip;
import com.google.android.material.chip.ChipGroup;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CategoryAdapter extends RecyclerView.Adapter<CategoryAdapter.CategoryViewHolder> {

    private Map<String, List<Medicine>> medicinesByCategory;
    private OnMedicineClickListener listener;

    public interface OnMedicineClickListener {
        void onMedicineClick(Medicine medicine);
    }

    public CategoryAdapter(Map<String, List<Medicine>> medicinesByCategory, OnMedicineClickListener listener) {
        this.medicinesByCategory = medicinesByCategory;
        this.listener = listener;
    }

    @NonNull
    @Override
    public CategoryViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_category_card, parent, false);
        return new CategoryViewHolder(view, listener);
    }

    @Override
    public void onBindViewHolder(@NonNull CategoryViewHolder holder, int position) {
        if (medicinesByCategory != null && !medicinesByCategory.isEmpty()) {
            String category = (String) medicinesByCategory.keySet().toArray()[position];
            holder.bind(category, medicinesByCategory.get(category));
        }
    }

    @Override
    public int getItemCount() {
        return medicinesByCategory == null || medicinesByCategory.isEmpty() ? 0 : medicinesByCategory.size();
    }

    // 更新数据的方法（用于分类结果）
    public void updateData(Map<String, List<Medicine>> newMedicinesByCategory) {
        medicinesByCategory = newMedicinesByCategory;
        notifyDataSetChanged(); // 通知适配器数据已更改
    }

    // 更新数据的方法（用于搜索结果）
    public void updateData(List<Medicine> searchResults) {
        // 将搜索结果转换为分类形式，或直接展示
        if (searchResults != null) {
            Map<String, List<Medicine>> categorizedSearchResults = newMedicinesToCategoryMap(searchResults);
            medicinesByCategory = categorizedSearchResults;
        } else {
            medicinesByCategory = null;
        }
        notifyDataSetChanged(); // 通知适配器数据已更改
    }

    // 将搜索结果按类别分组
    private Map<String, List<Medicine>> newMedicinesToCategoryMap(List<Medicine> medicines) {
        Map<String, List<Medicine>> categorized = new HashMap<>();
        for (Medicine medicine : medicines) {
            String category = medicine.getCategory();
            categorized.computeIfAbsent(category, k -> new ArrayList<>()).add(medicine);
        }
        return categorized;
    }

    public static class CategoryViewHolder extends RecyclerView.ViewHolder {
        private TextView titleTextView;
        private ChipGroup medicineChipGroup;
        private OnMedicineClickListener listener;

        public CategoryViewHolder(@NonNull View itemView, OnMedicineClickListener listener) {
            super(itemView);
            titleTextView = itemView.findViewById(R.id.titleTextView);
            medicineChipGroup = itemView.findViewById(R.id.medicineChipGroup);
            this.listener = listener;
        }

        public void bind(String category, List<Medicine> medicines) {
            titleTextView.setText(category);

            medicineChipGroup.removeAllViews();
            for (Medicine medicine : medicines) {
                Context context = new ContextThemeWrapper(itemView.getContext(), R.style.CustomChipStyle);
                Chip chip = new Chip(context);
                chip.setText(medicine.getName());
                chip.setChipBackgroundColorResource(R.color.chip_background_color);
                chip.setChipStrokeColor(ContextCompat.getColorStateList(itemView.getContext(), R.color.chip_stroke_color));
                chip.setChipStrokeWidth(1f);
                chip.setChipCornerRadius(16f);
                chip.setLayoutParams(new ChipGroup.LayoutParams(
                        ViewGroup.LayoutParams.WRAP_CONTENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT));

                chip.setOnClickListener(v -> {
                    if (listener != null) {
                        listener.onMedicineClick(medicine);
                    }
                });

                medicineChipGroup.addView(chip);
            }
        }
    }
}